package com.jvxb.modules.utils;

import com.jvxb.common.utils.DateUtil;
import com.jvxb.common.utils.FileUtil;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Random;

/**
 * 文件存储相关工具类
 * @author jvxb
 * @since 2020-06-14
 */
public class FileStoreUtil {

    public static String uploadPath = null;
    static {
        if(System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0){
            uploadPath = "E:\\demoResource\\upload";
        }else if(System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0){
            uploadPath = "/usr/demoResource/upload/";
        }
    }

    public static void fileDownload(final HttpServletResponse response, String filePath, String fileName)
            throws Exception {
        File excelFile = ResourceUtils.getFile("classpath:" + filePath);
        if (!excelFile.exists()) {
            throw new RuntimeException("file is not exists in:" + filePath);
        }
        byte[] data = FileUtil.toByteArray2(excelFile);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }

    /**
     *   上传Excel文件
     * @param file excel文件对象
     * @return 上传Excel的具体方法，返回excel的最终路径
     */
    public static String uploadExcel(MultipartFile file) {
        //目标地址 = 上传路径 + 文件名
        String targetPath = null;
        String uploadType = "excel";
        if (file != null && !file.isEmpty()) {
            // 设置实际的上传路径: 基本路径/类型/日期/
            String basePath = uploadPath;
            String nowDate = DateUtil.getDays();
            String realPath = formatUploadPath(basePath, uploadType, nowDate);
            // 设置上传的文件名称: 格式化以避免文件名重复
            String fileName = file.getOriginalFilename();
            fileName = formatFileName(fileName);
            try {
                //开始上传
                uploadFile(file.getBytes(), realPath, fileName);
                // 上传成功后，返回最终的上传地址
                targetPath = getExcelPath(uploadType, nowDate, fileName);
            } catch (Exception e) {
                return null;
            }
        }
        return targetPath;
    }

    /**
     * 设置上传路径：根据上传时间和上传类型设置
     */
    public static String formatUploadPath(String basePath, String type, String date) {
        String uploadPath = basePath + type + File.separator + date + File.separator;
        return uploadPath;
    }

    /**
     * 格式化文件名称, 避免文件名重复
     */
    public static String formatFileName(String fileName) {
        Random random = new Random();
        String prefix = fileName.getBytes().toString().substring(3);
        String midfix = new Date().getTime() + "";
        String random1 = random.nextInt(10) + "";
        String random2 = random.nextInt(10) + "";
        String suffix = fileName.replaceAll(".+(\\.\\w+)", "$1");
        String realName = prefix + midfix + random1 + random2 + suffix;
        return realName;
    }

    /**
     * @Description : 上传文件
     * @param file     : 上传的文件实体
     * @param filePath : 上传文件的目标路径
     * @param fileName : 文件名
     * @throws Exception
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    /**
     * 获取excel的位置, 即uploadSetting.properties中配置的路径 + excel + 日期 + excel名
     */
    public static String getExcelPath(String type, String nowDate, String fileName) {
        return uploadPath + type + File.separator + nowDate + File.separator + fileName;
    }

}
